<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;

use Common\Controller\AdminbaseController;
use Label\Model\CategoryModel;
use Portal\Model\PostsModel;
use Think\Cache\Driver\Redis;

class AdminPostController extends AdminbaseController {
    
	protected $posts_model;
	protected $term_relationships_model;
	protected $terms_model;
	
	function _initialize() {
		parent::_initialize();
		$this->posts_model = D("Portal/Posts");
		$this->terms_model = D("Portal/Terms");
		$this->term_relationships_model = D("Portal/TermRelationships");
	}
	
	// 后台文章管理列表
	public function index(){
	    $where['p.post_status']     = array('neq', PostsModel::POST_STATUS_DEL);
        $where['p.post_type']       = array(array('eq', PostsModel::POST_TYPE_ARTICLE), array('exp', 'IS NULL'), 'OR');
		$this->_lists($where);
        $this->display();
	}
	
	// 文章添加
	public function add(){
        $post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_ARTICLE, 'status' => 1])->order('id asc')->select();
        $this->assign('post_categorys', $post_categorys);
		$this->display();
	}
	
	// 文章添加提交
	public function add_post(){
		if (IS_POST) {
            $category = $_POST['post']['category'];
            if (empty($category)) {
                $this->error("请至少选择一个分类！");
            }
            $_POST['post']['category'] = implode(',', $category);

            $labels = $_POST['post']['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $_POST['post']['labels'] = implode(',', $labels);

			if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
				foreach ($_POST['photos_url'] as $key=>$url){
					$photourl=sp_asset_relative_url($url);
					$_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
				}
			}
			$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['thumb_local_path'] = sp_asset_relative_url($_POST['smeta']['thumb_local_path']);
			$_POST['post']['post_modified']=date("Y-m-d H:i:s",time());
			$article=I("post.post");

            // 作者按名字匹配
            if ($article['post_author_name']) {
                $user = get_user_by_name($article['post_author_name']);
                if ($user) {
                    $article['post_author'] = $user['id'];
                }
            }

			$article['smeta']=json_encode($_POST['smeta']);
			$article['post_content']=htmlspecialchars_decode($article['post_content']);
			$result=$this->posts_model->add($article);
			if ($result) {

			    // 主动提交百度seo链接
                if (C('PUSH_SEO_URL')) {
                    $urls = array(C('HTTP_METHOD') . C('DOMAIN_NAME') . U('Portal/Article/article_info', ['id' => $result]));
                    $re = post_baidu_seo_url($urls);
                    writeFile($urls);
                    writeFile($re);
                }

				$this->success("添加成功！");
			} else {
				$this->error("添加失败！");
			}
			 
		}
	}
	
	// 文章编辑
	public function edit(){
        $pre        = "posts_edit_";
        $id         = I('get.id', 0, 'intval');
        $key        = $pre . $id;
		$redis      = Redis::getinstance();
		$edit_id    = $redis->get($key);
		$admin_id   = session('ADMIN_ID');

		if ($edit_id && $edit_id != $admin_id) {
            $this->error('该文章正在被编辑，请稍后');
            exit;
        }

        $redis->set($key, $admin_id, C('POSTS_EDIT_TIME'));

		$post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_ARTICLE, 'status' => 1])->order('id asc')->select();
		$this->assign('post_categorys', $post_categorys);

		$post = $this->posts_model
            ->alias('p')
            ->where("id = $id")
            ->field('*, (select GROUP_CONCAT(name) FROM rx_label where FIND_IN_SET(id, p.labels) order by id) as label_names')
            ->find();

		if ($post && !empty($post['labels'])) {
		    $post['label_names'] = array_filter(explode(',', $post['label_names']));
        } else {
            $post['label_names'] = [];
        }
		$this->assign("post",$post);
		$this->assign("smeta",json_decode($post['smeta'],true));
		$this->display();
	}
	
	// 文章编辑提交
	public function edit_post(){
		if (IS_POST) {

			$post_id    = intval($_POST['post']['id']);
            $pre        = "posts_edit_";
            $key        = $pre . $post_id;
            $redis      = Redis::getinstance();
            $edit_id    = $redis->get($key);
            $admin_id   = session('ADMIN_ID');

            if ($edit_id && $edit_id != $admin_id) {
                $this->error('该文章正在被编辑，请稍后');
                exit;
            }
            $redis->del($key);

            $category = $_POST['post']['category'];
            if (empty($category)) {
                $this->error("请至少选择一个分类！");
            }
            $_POST['post']['category'] = implode(',', $category);

            $labels = $_POST['post']['labels'];
            $labels = array_filter(explode(',', $labels));
            if (empty($labels)) {
                $this->error("请至少选择一个标签！");
            }
            $_POST['post']['labels'] = implode(',', $labels);
			
			if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
				foreach ($_POST['photos_url'] as $key=>$url){
					$photourl=sp_asset_relative_url($url);
					$_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
				}
			}
			$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['smeta']['thumb_local_path'] = sp_asset_relative_url($_POST['smeta']['thumb_local_path']);
			unset($_POST['post']['post_author']);
			$_POST['post']['post_modified']=date("Y-m-d H:i:s",time());
			$article=I("post.post");

			// 作者按名字匹配
            if ($article['post_author_name']) {
                $user = get_user_by_name($article['post_author_name']);
                if ($user) {
                    $article['post_author'] = $user['id'];
                }
            }

			$article['smeta']=json_encode($_POST['smeta']);
			$article['post_content']=htmlspecialchars_decode($article['post_content']);

			// 删除原图
//            $old_article = $this->posts_model->where(['id' => $article['id']])->find();
//            if ($old_article) {
//                $smeta  = json_decode($old_article['smeta'], true);
//                $path   = "." . C("TMPL_PARSE_STRING.__UPLOAD__") . $smeta['thumb_local_path'];
//                if (file_exists($path)) {
//                    unlink($path);
//                }
//            }

			$result=$this->posts_model->save($article);
			if ($result!==false) {
				$this->success("保存成功！");
			} else {
				$this->error("保存失败！");
			}
		}
	}
	
	// 文章排序
	public function listorders() {
		$status = parent::_listorders($this->term_relationships_model);
		if ($status) {
			$this->success("排序更新成功！");
		} else {
			$this->error("排序更新失败！");
		}
	}
	
	/**
	 * 文章列表处理方法,根据不同条件显示不同的列表
	 * @param array $where 查询条件
	 */
	private function _lists($where = array()) {

		// 开始时间
		$start_time = I('request.start_time');
		if(!empty($start_time)){
		    $where['p.post_date'] = array(
		        array('EGT',$start_time)
		    );
		}

        // 结束时间
		$end_time=I('request.end_time');
		if(!empty($end_time)){
		    if(empty($where['p.post_date'])){
		        $where['p.post_date']=array();
		    }
		    array_push($where['p.post_date'], array('ELT',$end_time));
		}

		// 标题模糊搜索
		$keyword=I('request.keyword');
		if(!empty($keyword)) {
		    $where['p.post_title']=array('like',"%$keyword%");
		}

        // 作者模糊搜索
        $author=I('request.author');
        if(!empty($author)){
            $where['c.user_nicename']=array('like',"%$author%");
        }

        // 类型选择
        $category = I('request.category');
        if(!empty($category)){
            $where[] = 'FIND_IN_SET(' . $category . ', p.category)';
        }

        $count = $this->posts_model
            ->alias("p")
            ->join("__USERS__ c ON p.post_author = c.id", 'left')
            ->where($where)
            ->count();
        $page = $this->page($count, 20);

        // 文章分类
        $post_categorys = M('category')->where(['type' => CategoryModel::CATEGORY_TYPE_ARTICLE, 'status' => 1])->order('id asc')->select();
        $this->assign('post_categorys', $post_categorys);
	 
		$this->posts_model
            ->alias("p")
            ->join("__USERS__ c ON p.post_author = c.id", 'left')
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->field('p.*, c.user_nicename, c.user_login')
            ->order("p.post_order desc, p.post_date DESC");

		$posts = $this->posts_model->select();

		foreach ($posts as $k => $p) {
		    if (empty($p['user_nicename'])) {
		        $p['user_nicename'] = $p['user_login'];
		        $posts[$k] = $p;
            }
        }

		$this->assign("page", $page->show('Admin'));
		$this->assign("formget",array_merge($_GET,$_POST));
		$this->assign("posts",$posts);
	}
	
	// 获取文章分类树结构 select 形式
	private function _getTree(){
		$term_id=empty($_REQUEST['term'])?0:intval($_REQUEST['term']);
		$result = $this->terms_model->order(array("listorder"=>"asc"))->select();
		
		$tree = new \Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		foreach ($result as $r) {
			$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
			$r['visit'] = "<a href='#'>访问</a>";
			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
			$r['id']=$r['term_id'];
			$r['parentid']=$r['parent'];
			$r['selected']=$term_id==$r['term_id']?"selected":"";
			$array[] = $r;
		}
		
		$tree->init($array);
		$str="<option value='\$id' \$selected>\$spacer\$name</option>";
		$taxonomys = $tree->get_tree(0, $str);
		$this->assign("taxonomys", $taxonomys);
	}
	
	// 获取文章分类树结构 
	private function _getTermTree($term=array()){
		$result = $this->terms_model->order(array("listorder"=>"asc"))->select();
		$tree = new \Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		foreach ($result as $r) {
			$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
			$r['visit'] = "<a href='#'>访问</a>";
			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
			$r['id']=$r['term_id'];
			$r['parentid']=$r['parent'];
			$r['selected']=in_array($r['term_id'], $term)?"selected":"";
			$r['checked'] =in_array($r['term_id'], $term)?"checked":"";
			$array[] = $r;
		}

		$tree->init($array);
		$str="<option value='\$id' \$selected>\$spacer\$name</option>";
		$taxonomys = $tree->get_tree(0, $str);

        $this->assign("taxonomys", $taxonomys);
	}
	
	// 文章删除
	public function delete(){
		if(isset($_GET['id'])){
			$id = I("get.id",0,'intval');
			if ($this->posts_model->where(array('id'=>$id))->save(array('post_status'=>3)) !==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
		
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			
			if ($this->posts_model->where(array('id'=>array('in',$ids)))->save(array('post_status'=>3))!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}
	
	// 文章审核
	public function check(){
		if(isset($_POST['ids']) && $_GET["check"]){
		    $ids = I('post.ids/a');
			
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('post_status'=>1)) !== false ) {
				$this->success("审核成功！");
			} else {
				$this->error("审核失败！");
			}
		}
		if(isset($_POST['ids']) && $_GET["uncheck"]){
		    $ids = I('post.ids/a');
		    
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('post_status'=>0)) !== false) {
				$this->success("取消审核成功！");
			} else {
				$this->error("取消审核失败！");
			}
		}
	}
	
	// 文章产业轮播
	public function top(){
		if(isset($_POST['ids']) && $_GET["top"]){
			$ids = I('post.ids/a');
			
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>1))!==false) {
				$this->success("设置产业轮播成功！");
			} else {
				$this->error("设置产业轮播失败！");
			}
		}
		if(isset($_POST['ids']) && $_GET["untop"]){
		    $ids = I('post.ids/a');
		    
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>0))!==false) {
				$this->success("取消产业轮播成功！");
			} else {
				$this->error("取消产业轮播失败！");
			}
		}
	}
	
	// 文章首页轮播
	public function recommend(){
		if(isset($_POST['ids']) && $_GET["recommend"]){
			$ids = I('post.ids/a');
			
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
				$this->success("首页轮播成功！");
			} else {
				$this->error("首页轮播失败！");
			}
		}
		if(isset($_POST['ids']) && $_GET["unrecommend"]){
		    $ids = I('post.ids/a');
		    
			if ( $this->posts_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
				$this->success("取消首页轮播成功！");
			} else {
				$this->error("取消首页轮播失败！");
			}
		}
	}
	
	// 文章批量移动
	public function move(){
		if(IS_POST){
			if(isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])){
			    $old_term_id=I('get.old_term_id',0,'intval');
			    $term_id=I('post.term_id',0,'intval');
			    if($old_term_id!=$term_id){
			        $ids=explode(',', I('get.ids/s'));
			        $ids=array_map('intval', $ids);
			         
			        foreach ($ids as $id){
			            $this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$old_term_id))->delete();
			            $find_relation_count=$this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$term_id))->count();
			            if($find_relation_count==0){
			                $this->term_relationships_model->add(array('object_id'=>$id,'term_id'=>$term_id));
			            }
			        }
			    }
			    $this->success("移动成功！");
			}
		}else{
			$tree = new \Tree();
			$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
			$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
			$terms = $this->terms_model->order(array("path"=>"ASC"))->select();
			$new_terms=array();
			foreach ($terms as $r) {
				$r['id']=$r['term_id'];
				$r['parentid']=$r['parent'];
				$new_terms[] = $r;
			}
			$tree->init($new_terms);
			$tree_tpl="<option value='\$id'>\$spacer\$name</option>";
			$tree=$tree->get_tree(0,$tree_tpl);
			 
			$this->assign("terms_tree",$tree);
			$this->display();
		}
	}
	
	// 文章批量复制
	public function copy(){
	    if(IS_POST){
	        if(isset($_GET['ids']) && isset($_POST['term_id'])){
	            $ids=explode(',', I('get.ids/s'));
	            $ids=array_map('intval', $ids);
	            $uid=sp_get_current_admin_id();
	            $term_id=I('post.term_id',0,'intval');
	            $term_count=$terms_model=M('Terms')->where(array('term_id'=>$term_id))->count();
	            if($term_count==0){
	                $this->error('分类不存在！');
	            }
	            
	            $data=array();
	            
	            foreach ($ids as $id){
	                $find_post=$this->posts_model->field('post_keywords,post_source,post_content,post_title,post_excerpt,smeta')->where(array('id'=>$id))->find();
	                if($find_post){
	                    $find_post['post_author']=$uid;
	                    $find_post['post_date']=date('Y-m-d H:i:s');
	                    $find_post['post_modified']=date('Y-m-d H:i:s');
	                    $post_id=$this->posts_model->add($find_post);
	                    if($post_id>0){
	                        array_push($data, array('object_id'=>$post_id,'term_id'=>$term_id));
	                    }
	                }
	            }
	            
	            if ( $this->term_relationships_model->addAll($data) !== false) {
	                $this->success("复制成功！");
	            } else {
	                $this->error("复制失败！");
	            }
	        }
	    }else{
	        $tree = new \Tree();
	        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
	        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	        $terms = $this->terms_model->order(array("path"=>"ASC"))->select();
	        $new_terms=array();
	        foreach ($terms as $r) {
	            $r['id']=$r['term_id'];
	            $r['parentid']=$r['parent'];
	            $new_terms[] = $r;
	        }
	        $tree->init($new_terms);
	        $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
	        $tree=$tree->get_tree(0,$tree_tpl);
	
	        $this->assign("terms_tree",$tree);
	        $this->display();
	    }
	}
	
	// 文章回收站列表
	public function recyclebin(){
		$this->_lists(array('post_status'=>array('eq',3)));
		$this->_getTree();
		$this->display();
	}
	
	// 清除已经删除的文章
	public function clean(){
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			$ids = array_map('intval', $ids);
			$status=$this->posts_model->where(array("id"=>array('in',$ids),'post_status'=>3))->delete();
			$this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
			
			if ($status!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}else{
			if(isset($_GET['id'])){
				$id = I("get.id",0,'intval');
				$status=$this->posts_model->where(array("id"=>$id,'post_status'=>3))->delete();
				$this->term_relationships_model->where(array('object_id'=>$id))->delete();
				
				if ($status!==false) {
					$this->success("删除成功！");
				} else {
					$this->error("删除失败！");
				}
			}
		}
	}
	
	// 文章还原
	public function restore(){
		if(isset($_GET['id'])){
			$id = I("get.id",0,'intval');
			if ($this->posts_model->where(array("id"=>$id,'post_status'=>3))->save(array("post_status"=>"1"))) {
				$this->success("还原成功！");
			} else {
				$this->error("还原失败！");
			}
		}
	}


    // 设置文章编辑的状态
    public function occupy_post_edit()
    {
        $pre    = "posts_edit_";
        $id     = I('get.id', 0, 'intval');
        $key    = $pre . $id;
        $type   = I('get.type', '', 'strval');
        $type   = $type ? $type : 'del';

        if ($id) {
            $admin_id   = session('ADMIN_ID');
            $redis      = Redis::getinstance();
            $editTime   = C('POSTS_EDIT_TIME');
            $exists     = $redis->exists($key);
            if ($type == 'add') {
                if ($exists) {
                    $redis->set($key, $admin_id, $editTime);
                    $this->success('成功刷新状态');
                } else {
                    $this->error('状态更改，请保存修改内容，刷新页面');
                }
            } else {
                if ($exists) {
                    $edit_user_id = $redis->get($key);
                    if ($edit_user_id == $admin_id) {
                        $redis->del($key);
                        $this->success('成功刷新状态');
                    } else {
                        $this->error('状态更改，请保存修改内容，刷新页面');
                    }
                } else {
                    $this->success('状态更改，请保存修改内容，刷新页面');
                }
            }
        } else {
            $this->error('刷新数据有误，请保存修改内容，刷新页面');
        }
	}

	// 动态调整post排序
    public function change_post_order()
    {
        $id     = I('id', 0, 'intval');
        $order  = I('order', 0, 'intval');

        if ($id) {
            $this->posts_model->where(['id' => $id])->save(['post_order' => $order]);
            $this->success('修改成功');
        }
	}

	// 日报列表
    public function daily_report()
    {
        $where['p.post_status']     = PostsModel::POST_STATUS_NORMAL;
        $where['p.post_type']       = PostsModel::POST_TYPE_DAILY_REPORT;
        $this->_lists($where);
        $this->display();
	}


    // 日报编辑
    public function edit_daily_report(){

	    $id = I('id', 0, 'intval');
	    if (IS_POST) {
            $_POST['post']['post_modified'] = date("Y-m-d H:i:s", time());
            $article=I("post.post");

            // 作者按名字匹配
            if ($article['post_author_name']) {
                $user = get_user_by_name($article['post_author_name']);
                if ($user) {
                    $article['post_author'] = $user['id'];
                }
            }

            $article['post_content']    = htmlspecialchars_decode($article['post_content']);
            $article['post_type']       = PostsModel::POST_TYPE_DAILY_REPORT;

            if ($id) {
                // 编辑
                M('posts')->where(['id' => $id])->save($article);
            } else {
                // 新增
                unset($article['id']);
                $result = M('posts')->add($article);

                // 主动提交百度seo链接
                if (C('PUSH_SEO_URL')) {
                    $urls = array(C('HTTP_METHOD') . C('DOMAIN_NAME') . U('Portal/Article/daily_report_detail', ['id' => $result]));
                    post_baidu_seo_url($urls);
                }
            }

            $this->success("操作成功");

        } else {

	        if ($id) {
	            $post = M('posts')->where(['id' => $id])->find();
	            $this->assign('post', $post);
            }

            $this->display();
        }
    }
}